package h0828;

public class ReverseList {
    static class ListNode {
        int val;
        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(4, new ListNode(3, new ListNode(2, new ListNode(5))));
        ListNode res = getRes(head, 2, 4);
        while (res != null) {
            System.out.println(res.val);
            res = res.next;
        }
    }

    private static ListNode getRes(ListNode head, int left, int right) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode prev=dummy;
        for (int i = 0; i < left - 1; i++) {
            prev = prev.next; //使得dummy指向left节点
        }
        ListNode p=prev.next; //left
        ListNode q=p.next;    //紧跟着left
        //双指针
        for (int i = 0; i < right - left; i++) {
            p.next=q.next;
            q.next=prev.next; //这里得是不变的量
            prev.next=q;
            q=p.next;
        }
        return dummy.next;
    }
}
